package com.wusuowei.oauthserver.ucenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wusuowei.oauthserver.ucenter.mapper.UserMapper;
import com.wusuowei.oauthserver.ucenter.model.po.User;
import com.wusuowei.oauthserver.ucenter.service.ThreeUserService;
import me.zhyd.oauth.model.AuthUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;


/**
 * @description 第三方授权登录时，将用户信息保存到数据库中
 * @author LGY
 * @date 2023/03/31 17:20
 * @version 1.0.0
 */
@Service
public class ThreeUserServiceImpl implements ThreeUserService {

    @Autowired
    UserMapper userMapper;

    @Override
    @Transactional
    public User addUser(AuthUser authUser) {
        //先取出unionid
        String unionid = authUser.getUuid();
        //根据unionid查询数据库
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUnionid, unionid));
        if (user != null) {
            //该用户在系统存在
            user.setLoginDate(LocalDateTime.now());
            userMapper.updateById(user);
            return user;
        }
        user = new User();
        BeanUtils.copyProperties(authUser, user);
        user.setUnionid(unionid);
        user.setPassword(unionid);
        user.setStatus("1");//用户状态
        user.setLoginDate(LocalDateTime.now());
        userMapper.insert(user);
        return user;
    }
}
